'use strict';
const { Service } = require('egg');
const dayjs = require("dayjs");
const ModelName = 'UserPracticeRecord'
class RouterService extends Service {
  async getPage(where, page, pageSize) {
    return this.ctx.model[ModelName].findAndCountAll({
      where,
      offset: pageSize * (page - 1),
      limit: pageSize,
      order:[
        // id 降序
        ['created_time','DESC']
      ],
    });
  }
  // 所有列表
  async allList(where) {
    return this.ctx.model[ModelName].findAll({
      where: {
        ...where
      },
      order:[
        // id 降序
        ['created_time','DESC']
      ],
        include: [
            {
                model: this.ctx.model.User,
            },
            {
                model: this.ctx.model.Course,
            },
            {
                model: this.ctx.model.CourseCategories,
            },
            {
                model: this.ctx.model.UserPractice,
                include: [
                    {
                        model: this.ctx.model.Question,
                        include: [
                            {
                                model: this.ctx.model.QuestionOption,
                            }
                        ]
                    }
                ]
            }
        ]

    });
  }
  async findOne(id) {
    const findOneData = await this.ctx.model[ModelName].findOne({
      where: {
        id,
      },
        include: [
            {
                model: this.ctx.model.User,
            },
            {
                model: this.ctx.model.Course,
            },
            {
                model: this.ctx.model.CourseCategories,
            },
            {
                model: this.ctx.model.UserPractice,
                include: [
                    {
                        model: this.ctx.model.Question,
                        include: [
                            {
                                model: this.ctx.model.QuestionOption,
                            }
                        ]
                    }
                ]
            }
        ]
    });
      return {
            ...findOneData.dataValues,
      }
  }
  async submitUserPracticeRecord(data) {
      // 更新练习记录结果
        const { id, list } = data
        let status = 1
        let score = 0
          let correct_num = 0
            list.forEach(item => {
                if (item.is_correct) {
                    score+=item.score
                    correct_num++
                }
            })
          await this.ctx.model[ModelName].update({
                status,
                score,
                correct_num,
                end_time: dayjs(),
                is_lottery: correct_num >= 0 ? 0 : -1
          }, {
                where: {
                    id
                }
          })
          for (let i = 0; i < list.length; i++) {
              await this.ctx.model.UserPractice.update({
                    is_correct: list[i].is_correct,
                  selected_option: list[i].selected_option,
              }, {
                    where: {
                        id: list[i].id
                    }
              })
          }
        return this.findOne(id)
  }
  async create(data) {
    // 根据数量选择题目
    let { num, category_id, course_id } = data
    let name = '答题'
    let where = {}
    // 随机挑选num道题目
    const questionList = await this.ctx.model.Question.findAll({
        where: {
            ...where,
            status: 1,
        }
    })
      if (!questionList || questionList.length === 0) {
            throw new Error('没有题目，请联系管理员')
      }
    const questionIds = questionList.map(item => item.id)
    const selectedQuestionIds = []
    if (questionIds.length <= num) {
        selectedQuestionIds.push(...questionIds)
    }
    else {
        for (let i = 0; i < num; i++) {
            const randomIndex = Math.floor(Math.random() * questionIds.length)
            selectedQuestionIds.push(questionIds[randomIndex])
            questionIds.splice(randomIndex, 1)
        }
    }
    // 根据数量创建时间 一题5分钟
    data.minutes = 99
      // 计算总分
      let total_score = 0
      if (selectedQuestionIds.length > 0) {
          total_score = questionList.filter(item => selectedQuestionIds.includes(item.id)).reduce((prev, current) => {
              return prev + current.score
          },0)
      }
      // 创建数据
      const createData = await this.ctx.model[ModelName].create({
          ...data,
          num: selectedQuestionIds.length,
          total_score,
          name
      });
    const record_id = createData.dataValues.id
    // 创建用户练习记录
    const userPracticeList = selectedQuestionIds.map(question_id => {
        return {
            record_id,
            user_id: data.user_id,
            question_id,
        }
    })
    await this.ctx.model.UserPractice.bulkCreate(userPracticeList)
    return createData
  }
  async update(id, data) {
    return await this.ctx.model[ModelName].update(data, { where: { id } });
  }
  async deleteById(id) {
    return await this.ctx.model[ModelName].update({
        delete_flag: 1
    }, { where: { id } });
  }
}

module.exports = RouterService;
